package com.guw.TestThread;

//死锁,多个线程互相抱着对方需要的资源,形成僵持
public class TestDeadLock {
    public static void main(String[] args) {
        PlayToy playToy1 = new PlayToy(0, "guauga");
        PlayToy playToy2 = new PlayToy(1, "doudou");
        new Thread(playToy1).start();
        new Thread(playToy2).start();
    }
}

class Toy1 {
}

class Toy2 {
}

class PlayToy implements Runnable {
    static Toy1 toy1 = new Toy1();
    static Toy2 toy2 = new Toy2();

    int choice;
    String name;

    public PlayToy(int choice, String name) {
        this.choice = choice;
        this.name = name;
    }

    @Override
    public void run() {
        playToy();

    }

    private void playToy() {
        if (choice == 0) {
            //锁包里面含一个锁包,才会被锁死,如果不是包含关系,就不会被锁死了!!!
            synchronized (toy1) {
                System.out.println(this.name + "玩toy1");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (toy2) {
                    System.out.println(this.name + "玩toy2");
                }
            }
        } else if (choice == 1) {
            synchronized (toy2) {
                System.out.println(name + "玩toy2");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (toy1) {
                    System.out.println(name + "玩toy1");
                }
            }
        }
    }
}
